package actions;

import java.io.BufferedInputStream;
import java.io.IOException;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class LocalWeatherAct implements Action{

	public static final String cmd="wea";
	final String cmd1="wea on";
	final String cmd2="wea off";
	
	boolean isOn=false;
	@Override
	public boolean checkCmd(String cmd) {
		if(cmd.equals(cmd1)){
			isOn=true;
			return true;
		}else if(cmd.equals(cmd2)){
			isOn=false;
			return true;
		}else return false;
	}

	@Override
	public void setHandles(Object... hdls) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public Object call() throws Exception {
		
		String rs="Thank you for apply local weather service";
		if(isOn){
			shutdown();
		}else{
		timer.schedule(weaTask, 1000*60*60*24);
		}
		return rs;
	}
	
	
	/**
	 * task for getting weather by REST API
	 */
	//private ExecutorService  executor=Executors.newScheduledThreadPool(1);
	Timer timer=new Timer();
	LocalWeatherTask weaTask=new LocalWeatherTask();
	String content;
	private void shutdown(){
		//executor.shutdown();
		
		timer.cancel();
	}
	class LocalWeatherTask extends TimerTask{

		@Override
		public void run() {
			try {
				URL url=new URL("http://weather-china.appspot.com/api?city=beijing");
				URLConnection conn=url.openConnection();
				conn.setRequestProperty("User-Agent", "firefox");
				
				BufferedInputStream bis=new BufferedInputStream(conn.getInputStream());
				char c;
				StringBuffer sb=new StringBuffer();
				while((c=(char) bis.read())!=0){
					sb.append(c);
				}
				content=sb.toString();
				
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}		
		}
		
	}
}
